package servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.Factoty.DaoFactory;
import domain.Order;
import service.Factory.ServiceFactory;

/**
 * Servlet implementation class FindOrdersServlet
 */
@WebServlet("/FindOrdersServlet")
public class FindOrdersServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FindOrdersServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		List<Order> orders = null;
		String id = request.getParameter("id");
		String name = request.getParameter("receiverName");
		int page = request.getParameter("page") == null ? 1 : Integer.parseInt(request.getParameter("page"));
		int limit = 5;
		
		try {
			if ((id != null && !id.isEmpty()) || (name != null && !name.isEmpty())) {
				orders = ServiceFactory.getOrderServiceInstance().findOrder(id, name, page, limit);
			} else {
				orders = ServiceFactory.getOrderServiceInstance().findAllOrder(page, limit);
			}
			
			request.setAttribute("orders", orders);
			request.setAttribute("_page", page);
			request.setAttribute("hasPrev", page > 1);
			request.setAttribute("hasNext", orders.size() == limit);
			request.getRequestDispatcher("/server/login/home.jsp?item=orders").forward(request, response);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("err " + e.toString());
		}
	}

}
